<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" v-model="keyword" placeholder="请输入角色名称"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="handleFind">查找</el-button>
      <el-button type="primary" @click="handleAdd" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="tableData" v-loading="Loading" style="width: 100%" stripe>
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号" width="60" align="center">
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" min-width="150" align="center">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
          <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="block">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog v-if="dialogFormVisible" :title="title" :visible.sync="dialogFormVisible" width="500px"
      :close-on-click-modal="false" :before-close="handleDialogClose">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose()">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, editRole, deleteRole } from "@/api/role";
import { getAllMenu } from "@/api/categoryMenu";
export default {
  data() {
    return {
      Loading: true,
      handleMenuUidArr: [],  //筛选过后，没有子菜单的一二级菜单uid
      keyword: "",
      tableData: [],
      //所有菜单列表
      categoryMenuList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0, //总数量
      title: "增加角色",
      dialogFormVisible: false, //控制弹出框
      formLabelWidth: "80px",
      isEditForm: false,
      // tree配置项
      defaultProps: {
        children: "childCategoryMenu",
        label: "name",
      },
      form: {
        id: null,
        name: null
      },
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在1到20个字符" },
        ],
      },
    };
  },
  created() {
    this.roleList();
    // this.allMenuList();
  },
  methods: {
    //初始化菜单tree
    allMenuList: function () {
      getAllMenu().then((response) => {
          var categoryMenuList = response.data;
          this.categoryMenuList = categoryMenuList;
          //筛选一二级菜单，如果有子菜单，加入到数组中，用于tree中去除显示没有子菜单的选框勾
          for (let a = 0; a < categoryMenuList.length; a++) {
            if (categoryMenuList[a].childCategoryMenu) {
              this.handleMenuUidArr.push(categoryMenuList[a].uid)
              for (let b = 0; b < categoryMenuList[a].childCategoryMenu.length; b++) {
                if (categoryMenuList[a].childCategoryMenu[b].childCategoryMenu) {
                  this.handleMenuUidArr.push(categoryMenuList[a].childCategoryMenu[b].uid)
                }
              }
            }
          }
      });
    },

    roleList() {
      this.Loading = true;
      getRoleList().then((response) => {
          this.tableData = response.data.data;
          // this.total = response.data.total;
          this.Loading = false;
      });
    },

    handleFind() {
      this.roleList();
    },
    handleAdd() {
      this.title = "增加角色";
      this.isEditForm = false;
      this.dialogFormVisible = true;
    },
    handleEdit(row) {
      // for (var a = 0; a < this.handleMenuUidArr.length; a++) {
      //   row.categoryMenuUidList.forEach((item, index, arr) => {
      //     if (this.handleMenuUidArr[a] === item) {
      //       arr.splice(index, 1)
      //     }
      //   });
      // }
      this.title = "编辑角色";
      this.isEditForm = true;
      Object.assign(this.form, row);
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys(this.form.categoryMenuUidList);
      })

    },
    handleDelete(row) {
      this.$confirm("此操作将把角色删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRole(row.id).then((response) => {
              this.$message({
                type: "success",
                message: response.data,
              });
            this.roleList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // //得到选中树的UID
          // var categoryMenuUids = this.$refs.tree.getCheckedKeys();
          // // 得到的半选UID(也就是父级菜单)
          // var halfCategoryMenuUids = this.$refs.tree.getHalfCheckedKeys();
          // // 合并
          // categoryMenuUids = categoryMenuUids.concat(halfCategoryMenuUids);
          // //转换成字符串
          // this.form.categoryMenuUids = JSON.stringify(categoryMenuUids);
          if (this.isEditForm) {
            editRole(this.form).then((response) => {
                this.$message({
                  type: "success",
                  message: response.data,
                });
                this.handleDialogClose();
                this.roleList();
            });
          } else {
            addRole(this.form).then((response) => {
                this.$message({
                  type: "success",
                  message: response.data,
                });
                this.handleDialogClose();
                this.roleList();
            });
          }
        }
      });
    },
    handleDialogClose() {
      this.form = {
        uid: null,
        roleName: null,
        summary: null,
        categoryMenuUids: null, //已选择的
        categoryMenuUidList:[]  //已选择的
      };
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys(this.form.categoryMenuUidList);
        this.dialogFormVisible = false;
      })

    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.roleList();
    },
  },
};
</script>
